package com.zbkj.crmeb.handler.orderdelivery;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.utils.monitor.DingMsgEnum;
import com.utils.monitor.DingTalkMsgUtil;
import com.zbkj.crmeb.express.model.Express;
import com.zbkj.crmeb.express.service.ExpressService;
import com.zbkj.crmeb.handler.orderconfirm.AbstractOrderConfirmHandler;
import com.zbkj.crmeb.handler.orderconfirm.OrderConfirmContext;
import com.zbkj.crmeb.plat.by.dto.ByCommonConstant;
import com.zbkj.crmeb.store.model.OrderInfoDelivery;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderInfo;
import com.zbkj.crmeb.store.service.OrderInfoDeliveryService;
import com.zbkj.crmeb.store.service.StoreOrderInfoService;
import com.zbkj.crmeb.store.service.StoreOrderService;
import com.zbkj.crmeb.task.plat.bieyang.dto.BieYangOrderDeliveryDto;
import com.zbkj.crmeb.task.plat.bieyang.enums.ExpressEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author: wsl
 * @date: 2024/2/22 0022 22:28
 * @ClassName: ByOrderConfirmHandler
 */
@Component("byOrderDeliveryHandler")
public class ByOrderDeliveryHandler extends AbstractOrderConfirmHandler {
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private OrderInfoDeliveryService orderInfoDeliveryService;
    @Autowired
    private ExpressService expressService;
    @Value("${by.plat.url}")
    private String platUrl;

    @Value("${by.plat.key}")
    private String platKey;
    private static final Logger logger = LoggerFactory.getLogger(ByOrderDeliveryHandler.class);

    @Override
    public boolean doPreCheck(OrderConfirmContext context) {
        if (null == context || null == context.getStoreOrderInfo() || null == context.getStoreOrder()){
            return false;
        }
        StoreOrderInfo storeOrderInfo = context.getStoreOrderInfo();
        return storeOrderInfo.getChildOrderNumber().contains("BY");
    }

    @Override
    public boolean doHandler(OrderConfirmContext context) {
        logger.info("别样订单物流回传入口:{}",JSON.toJSONString(context));
        StoreOrderInfo storeOrderInfo = context.getStoreOrderInfo();
        Integer id = storeOrderInfo.getId();
        StoreOrder storeOrder = context.getStoreOrder();
        String orderId = storeOrder.getOrderId();
        String outOrderId = storeOrder.getOutOrderId();
        OrderInfoDelivery orderInfoDelivery = orderInfoDeliveryService.getOne(Wrappers.<OrderInfoDelivery>lambdaQuery().eq(OrderInfoDelivery::getOrderInfoId, id).orderByDesc(OrderInfoDelivery::getCreateTime).last("limit 1"));
        if (null == orderInfoDelivery){
            logger.error("订单发货记录为空");
            return false;
        }
        Integer expressId = orderInfoDelivery.getExpressId();
        Express express = expressService.info(expressId);
        if (null == express){
            logger.error("不存在的物流信息");
            return false;
        }

        // 向别样平台回传物流单号
        MultiValueMap<String,String> header = new LinkedMultiValueMap<>();
        header.put("Authorization",Collections.singletonList(platKey));

        BieYangOrderDeliveryDto bieYangOrderDeliveryDto = new BieYangOrderDeliveryDto();
        bieYangOrderDeliveryDto.setCarrier(ExpressEnum.getKeyByCode(expressId));
        bieYangOrderDeliveryDto.setCarrierName(express.getName());
        bieYangOrderDeliveryDto.setTrackingNumber(orderInfoDelivery.getDeliveryNumber());
        // 拆单逻辑
        assembledSplitOrderInfo(bieYangOrderDeliveryDto,storeOrder);
        Map<String, List<BieYangOrderDeliveryDto>> params = new HashMap<>();
        params.put("packageInfo",Collections.singletonList(bieYangOrderDeliveryDto));

        String url = String.format(platUrl+"/order/api/v1/orders/%s/delivery",storeOrder.getOutOrderId());
        logger.info("别样订单物流回传参数:{}；{}",url, JSON.toJSONString(params));
        String result = post(url, JSON.toJSONString(params), header);
        logger.info("别样订单物流回传结果:{}",result);
        DingTalkMsgUtil.sendMsg(DingMsgEnum.PLAT,"别样订单物流回传结果:"+result+";入参: "+JSON.toJSONString(params));
        return true;
    }

    private void assembledSplitOrderInfo(BieYangOrderDeliveryDto bieYangOrderDeliveryDto, StoreOrder storeOrder) {
        if (!Objects.equals(storeOrder.getFeature(ByCommonConstant.IS_SPLIT),ByCommonConstant.IS_Y)){
            return;
        }
        List<StoreOrderInfo> storeOrderInfos = storeOrderInfoService.list(Wrappers.<StoreOrderInfo>lambdaQuery().eq(StoreOrderInfo::getOrderId, storeOrder.getId()));
        if (CollectionUtils.isEmpty(storeOrderInfos)){
            return;
        }
        int index = 0;
        List<BieYangOrderDeliveryDto.skuInfo> skuInfos = new ArrayList<>();
        for (StoreOrderInfo storeOrderInfo : storeOrderInfos) {
            BieYangOrderDeliveryDto.skuInfo skuInfo = new BieYangOrderDeliveryDto.skuInfo();
            skuInfo.setMerchantSkuId(storeOrderInfo.getFeature("merchantSkuId"));
            skuInfo.setProductId(storeOrderInfo.getFeature("productId"));
            skuInfo.setSkuId(storeOrderInfo.getFeature("skuId"));
            skuInfo.setSkuIndex(index);
            index++;
        }
        bieYangOrderDeliveryDto.setSkuInfo(skuInfos);
    }


    public static String post(String url, String params, MultiValueMap<String, String> headers) {
        return request(url, params, headers, HttpMethod.POST, MediaType.APPLICATION_JSON);
    }

    /**
     * http请求
     *
     * @param url
     * @param params    请求参数
     * @param headers   请求头
     * @param method    请求方式
     * @param mediaType 参数类型
     * @return
     */
    public static String request(String url, Object params, MultiValueMap<String, String> headers, HttpMethod method, MediaType mediaType) {
        if (url == null || url.trim().isEmpty()) {
            return null;
        }
        RestTemplate client = new RestTemplate();
        // header
        HttpHeaders httpHeaders = new HttpHeaders();
        if (headers != null) {
            httpHeaders.addAll(headers);
        }
        // 提交方式：表单、json
        httpHeaders.setContentType(mediaType);
        HttpEntity<Object> httpEntity = new HttpEntity(params, httpHeaders);
        ResponseEntity<String> response = client.exchange(url, method, httpEntity, String.class);
        return response.getBody();
    }
}
